/*
 * @Author: c
 * @Date: 2023-12-04 21:49:59
 * @LastEditTime: 2024-02-02 23:04:03
 * @LastEditors: c
 * @Description:
 * @FilePath: \music-web-admin\src\utils\index.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
dayjs.extend(duration);

/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isBoolean(val: any) {
  return Object.prototype.toString.call(val) === "[object Boolean]";
}

/**
 * 播放时长格式化
 * @param ms
 * @returns
 */
export const durationFormat = (ms: number, milliseconds?: boolean) => {
  if (milliseconds) {
    return ms ? dayjs(ms).format("mm:ss.SSS") : "00:00.000";
  }

  if (!ms) {
    return "00:00";
  }
  if (ms < 1000 * 60 * 60) {
    // 如果小于1小时
    return dayjs.duration(ms).format("mm:ss");
  } else if (ms < 1000 * 60 * 60 * 24) {
    // 如果小于24小时
    return dayjs.duration(ms).format("HH:mm:ss");
  }
};

const windows: any = window;
export const checkMediaFile = (file: File): Promise<any> => {
  return new Promise((r, j) => {
    const getSize = () => file.size;
    const readChunk = (chunkSize: any, offset: any) =>
      new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event: any) => {
          if (event.target.error) {
            reject(event.target.error);
          }
          resolve(new Uint8Array(event.target.result));
        };
        reader.readAsArrayBuffer(file.slice(offset, offset + chunkSize));
      });

    windows
      .MediaInfo()
      .then((media: any) => {
        media
          .analyzeData(getSize, readChunk)
          .then((result: any) => {
            r(result);
          })
          .catch((error: any) => {
            j(error);
          });
      })
      .catch((error: any) => {
        j(error);
      });
  });
};
